<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    table{
      border-collapse: collapse;
      width:50%;
    }
    td, th{
      font-size: 20px;
      text-align: center;
      border: 1px solid #000;
    }
    caption{
      font-size: 30px;
      font-weight: bold;
    }
  </style>
</head>
<body>
  <div id="root">
    <h1>请登入以后再做操作</h1>
  <form>
    <div>
      <input type="text" id="username">
    </div>
    <div>
      <input type="password" id="password">
    </div>
    <button id="btn" type="button">登录</button>
  </form>
  </div>
  <script>

    function loadData() {
      const token = localStorage.getItem("token")
      fetch("http://localhost:3000/students",{
        method:"get",
        headers:{
          //Bearer xxxx
          "authorization":"Bearer " + token
        }
      })
      .then(res => {
        
        if(res.status === 200) {
          //res.json() 读取json格式数据
          return res.json()
        } else {
          throw new Error("请求加载失败")
        }
        
      }).then(res=>{
        //获取到数据
        const data = document.querySelector("#data")
        if(res.status == "ok") {
          const table = document.createElement("table")
          data.appendChild(table)
          table.insertAdjacentHTML("beforeend","<caption>学生列表</caption>")
          table.insertAdjacentHTML("beforeend",'<thead><tr><th>学号</th><th>姓名</th><th>年龄</th><th>地址</th></tr></thead>'
          )
          const tbody = document.createElement("tbody")
          table.appendChild(tbody)
          for(let stu of res.result) {
            table.insertAdjacentHTML("beforeend","<tr>" + "<th>" + stu.id + "</th>" +
              "<th>" + stu.name + "</th>" + "<th>" + stu.age + "</th>" + "<th>" + stu.address + "</th>" + "</tr>")
          }

        }
}).catch(err => {
        console.log("出错了",err);
      })
    }



    const root = document.querySelector("#root")
    //点击btn后实现登录功能
    const btn = document.querySelector("#btn")
   
    if(localStorage.getItem("token")) {
      //用户已经登录
      root.innerHTML = "<h1>欢迎" + localStorage.getItem("nickname") + '</h1> <button id="bt" onclick="loadData()">加载数据</button><button onclick="localStorage.clear()">注销</button><hr><div id="data"></div>'
    } else {
      btn.onclick = () => {
      //获取用户输入的用户名和密码
      const username = document.querySelector("#username").value.trim()
      const password = document.querySelector("#password").value.trim()
      //调用fetch完成登录
      fetch("http://localhost:3000/login",{
        method:"POST",
        headers:{
          "Content-type":"application/json"
        },
        body:JSON.stringify({
          username,password
        })
      }).then((res)=>{
        return res.json()
      }).then((res)=>{
        if(res.status != "ok"){
          throw new Error("用户名或密码错误")
        } else {
          //登录成功后，我们要把信息存储到本地
          /*
            sessionStorage 中存储的数据页面一关，数据就会丢失
            localStorage 存储时间比较长
          */
         localStorage.setItem("token",res.result.token)
         localStorage.setItem("nickname",res.result.nickname)
         
         root.innerHTML = "<h1>欢迎" + localStorage.getItem("nickname") + '</h1> <button id="bt" onclick="loadData()">加载数据</button><button onclick="localStorage.clear()">注销</button><hr><div id="data"></div>'
        }
        
      }).catch(()=>{
        console.log("出错了");
      })

    }
    }


    
  </script>
</body>
</html>